import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/export_tender_dialog.dart';
import 'package:tender_flutter/dialog/normal_text_dialog.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/helper/badge_manager.dart';
import 'package:tender_flutter/page/subscription/api/api_subscription.dart';
import 'package:tender_flutter/page/subscription/item/subscription_group_cell.dart';
import 'package:tender_flutter/page/subscription/model/subscription_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/animation_dialog.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class TabSubscriptionPage extends StatefulWidget {
  @override
  _TabSubscriptionPageState createState() => _TabSubscriptionPageState();
}

class _TabSubscriptionPageState extends State<TabSubscriptionPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<SubscriptionEntity>> _listFuture;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  /// 列表数据
  List<SubscriptionList> _dataLists = [];

  /// 手动刷新数据
  /// animation 如果可以使用下拉刷新组件，是否使用动画
  void _manualRefersh({bool animation = true}) {
    if (_loadState == LoadState.State_Success &&
        _refreshController != null &&
        animation == true) {
      _refreshController.requestRefresh();
    } else {
      _onRefresh();
    }
  }

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<SubscriptionEntity>> _getData() async {
    BadgeManager.instance.updateSubscriptionNum();

    var response = await ApiSubscription.subscriptionList<SubscriptionEntity>(
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  /// 删除订阅
  Future _deleteData(int position, int subId) async {
    var response = await ApiSubscription.deleteSubscription(subId: subId);
    if (response.status == Status.SUCCESS) {
      ToastUtils.show("删除成功");
      setState(() {
        _dataLists.removeAt(position);
      });
    }
  }

  FutureBuilder<ApiResponse<SubscriptionEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<SubscriptionEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              SubscriptionEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initBody(),
            emptyWidget: _emptyView(),
          );
        });
  }

  /// 导出信息
  _exportTenderInfo() {
    showExportInfoDialog();
  }

  /// 导出弹窗
  Future showExportInfoDialog() async {
    return await showGeneralDialog(
        context: context,
        pageBuilder: (context, anim1, anim2) {},
        barrierDismissible: true,
        barrierLabel: "",
        transitionDuration: Duration(milliseconds: 300),
        transitionBuilder: (context, anim1, anim2, child) {
          return Transform.scale(
              scale: anim1.value,
              child: Opacity(
                opacity: anim1.value,
                child: ExportTenderDialog(),
              ));
        });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
  }

  @override
  void didUpdateWidget(covariant TabSubscriptionPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("订阅服务", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
      actions: <Widget>[
        InkWell(
            onTap: () {
              LRouter.navigatorCtx(context)
                  .push(Routes.subscriptionCreatePage)
                  .then((value) => {
                        if (value ?? false)
                          {
                            // 需要刷新页面
                            _manualRefersh(animation: false)
                          }
                      });
            },
            child: IntrinsicHeight(
              child: Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(
                      left: ScreenAdapter.width(15),
                      right: ScreenAdapter.width(30)),
                  child: Text("+添加",
                      style: TextStyle(color: ThemeColors.colorType6))),
            )),
      ],
      isShowLeading: false,
    );
  }

  /// 内容体
  Widget _initBody() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
          physics: BouncingScrollPhysics(),
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            SubscriptionList model = _dataLists[index];
            return SubscriptionGroupListCell(
              data: model,
              onTapCallback: () {
                LRouter.navigatorCtx(context)
                    .push(Routes.subscriptionListPage,
                        arguments: SubscriptionListPageArguments(
                            subscriptionId: model.id, keywords: model.keyword))
                    .then((value) {
                  _manualRefersh(animation: false);
                });
              },
              exportCallback: () {
                _exportTenderInfo();
              },
              editCallback: () {
                LRouter.navigatorCtx(context)
                    .push(Routes.subscriptionCreatePage,
                        arguments: SubscriptionCreatePageArguments(
                            subscriptionInfo: model))
                    .then((value) => {
                          if (value ?? false)
                            {
                              // 需要刷新页面
                              _manualRefersh(animation: false)
                            }
                        });
              },
              deleteCallback: () async {
                var result = await showAnimationDialog(
                    context: context,
                    transitionType: TransitionType.rotation,
                    builder: (context) {
                      return NormalTextDialog(
                        content: "确定删除此条订阅信息？",
                      );
                    });
                if (result == AppConstant.DIALOG_ACTION_CONFIRM) {
                  _deleteData(index, model.id);
                }
              },
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorTransparent,
            );
          },
        ));
  }

  Widget _emptyView() {
    return Container(
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(RPath.imgPath + 'img_empty.png',
                width: ScreenAdapter.width(200),
                height: ScreenAdapter.height(200)),
            SizedBox(height: ScreenAdapter.height(30)),
            Text(
              "您还未订阅任何信息!",
              style: TextStyle(
                  color: ThemeColors.colorType50,
                  fontSize: ScreenAdapter.sp(30)),
            ),
            Text(
              "\n订阅成功后，第一时间推送符合条件的招投标信息\n实时推送 不再漏标",
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: ThemeColors.colorType62,
                  fontSize: ScreenAdapter.sp(24)),
            ),
            GestureDetector(
              child: Container(
                  height: ScreenAdapter.height(90),
                  width: ScreenAdapter.width(600),
                  margin: EdgeInsets.only(top: ScreenAdapter.height(100)),
                  decoration: BoxDecoration(
                      color: ThemeColors.colorType6,
                      borderRadius:
                          BorderRadius.circular(ScreenAdapter.width(14))),
                  child: FlatButton(
                      onPressed: () {
                        LRouter.navigatorCtx(context)
                            .push(Routes.subscriptionCreatePage)
                            .then((value) => {
                                  if (value ?? false)
                                    {
                                      // 需要刷新页面
                                      _manualRefersh()
                                    }
                                });
                      },
                      child: Text("立即订阅",
                          style: TextStyle(
                              color: ThemeColors.colorWhite,
                              fontSize: ScreenAdapter.sp(32))))),
            )
          ],
        ));
  }
}
